<?php
set_time_limit(0);
require 'db.php';

$results = DB::query("select * from city");
DB::query("delete from county");

foreach ($results as $row) {
    $code = substr($row['code'], 0, 4);
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, "http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2018/" . substr($code, 0, 2) . "/{$code}.html");
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($curl);
    curl_close($curl);
    
    $data = mb_convert_encoding($data, 'UTF-8', 'GBK');
    
    // 裁头
    $offset = @mb_strpos($data, 'countytr', 2000, 'GBK');
    if (!$offset) {
        continue;
    }
    $data = mb_substr($data, $offset, null, 'GBK');
    
    // 裁尾
    $offset = mb_strpos($data, '</table>', 0, 'GBK');
    $data = mb_substr($data, 0, $offset, 'GBK');
    preg_match_all('/\d{12}|[\x7f-\xff]+/', $data, $out);
    $out = $out[0];
    
    $lists = array();
    for ($j = 0; $j < count($out); $j++) {
        $lists[] = array(
            'cid' => $code,
            'code' => $out[$j++],
            'name' => $out[$j]
        );
    }
    
    DB::insert('county', $lists);
}

echo 'county插入成功';